package com.google.code.dhillon;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

/**
 * Based on the Notepad example found at:
 * http://developer.android.com/guide/tutorials/notepad/index.html
 */
public class LostDbAdapter {
	// these can be used outside of this class to
	public static final String KEY_NAME = "name";
	public static final String KEY_DESC = "desc";
	public static final String KEY_BIO = "bio";
	public static final String KEY_TITLE = "title";
	public static final String KEY_BODY = "body";
	public static final String KEY_ROWID = "_id";

	private static final String TAG = LostDbAdapter.class.getSimpleName();

	private DatabaseHelper mDbHelper;
	private SQLiteDatabase mDb;

	/**
	 * Database creation sql statement
	 */
	private static final String DATABASE_CREATE = "CREATE TABLE characters (_id integer primary key autoincrement, "
			+ "name text not null, desc text not null, bio text not null);";

	private static final String DATABASE_NAME = "lost";
	private static final String DATABASE_TABLE = "characters";
	private static final int DATABASE_VERSION = 1;

	private final Context mCtx;

	private static class DatabaseHelper extends SQLiteOpenHelper {

		DatabaseHelper(Context context) {
			super(context, DATABASE_NAME, null, DATABASE_VERSION);
		}

		// init table and preload data
		@Override
		public void onCreate(SQLiteDatabase db) {
			// create the table
			db.execSQL(DATABASE_CREATE);

			// insert prefill data
			String[] names = new String[] { "Jack Shephard", "Kate Austen",
					"James \"Sawyer\" Ford", "John Locke", "Hugo \"Hurley\" Reyes",
					"Benjamin Linus", "Sayid Jarrah" };
			String[] descs = new String[] {
					"Spinal surgeon at St. Sebastian Hospital in Los Angeles",
					"Fugitive and a Con Artist",
					"Con man",
					"Owner of a home inspection business, then Regional Collections Supervisor for a box company",
					"Multimillion dollar lottery winner. Before that, he worked at Mr. Clucks chicken restaurant.",
					"Dharma employee and then later one of the leaders of the Others",
					"Communications officer in the Iraqi Republican Guard" };
			String[] bios = new String[] {
					"Jack miraculously saved a woman, Sarah, and then married her. She later left him for another man. At one point, Jack suspected that Sarah was seeing his overbearing father, who, like Jack, was a spinal surgeon at St. Sebastian hospital.Jack accused his alcoholic father, Christian Shephard, of sleeping with his wife, and also turned him in to the medical board for operating while under the influence.Jack went to Phuket, where he met Achara, and Christian went on a drinking binge in Australia, and that is believed to be the cause of his death. Jack went to Australia to search for him at his mother's insistence, and was returning to the states with his father's body when the plane went down.",
					"Kate was on the run from the age of 24 after blowing up her mother's house with her stepfather inside. She had just learned that her stepfather was actually her biological father. Previously she had believed her father was Sergeant Sam Austen.Marshal Edward Mars caught Kate, but she got away. He continued to pursue her.Kate went by many different names, at one point going by Lucy and working with Cassidy to see her mother. At another point, as Monica, she got married. She called the Marshal and begged him to stop chasing her, but he said he would only if she stopped running. Kate left her husband.",
					"His birth name is James Ford. When he was young, his father killed his mother and then himself after the couple was conned by a man named Sawyer. When he grew up, Sawyer took on the name of the con man and learned to con.One of his cons, Cassidy, figured out what he was doing and asked to be a part of it. The two conned together for awhile until he conned her. He ended up in prison, where Cassidy visited him to tell him he has a daughter.Sawyer made a deal with the warden and was let out of prison. He anonymously sent his reward money to Cassidy's daughter.He got news of where the real Sawyer was and went to Australia to kill him. After shooting the man, Sawyer realized that he had been conned and the man he shot was not the real Sawyer.",
					"John Locke was not raised by his biological parents. He was sent from foster home to foster home and didn't know his biological mother and father until his mother found him and scammed him into thinking that he'd found his biological father on his own. His father, Anthony Cooper, befriended him, and then let it slip that he needed a kidney transplant. Locke was quick to offer his kidney, but after the operation, his father didn't want anything to do with him. Locke was obsessed with wanting to know why his father didn't want his friendship.He met Helen and they began a relationship, but she wanted him to stop watching his father. He couldn't do this and Helen left him.When Locke found out that his father was conning a family, he interceded and his father pushed him out of an eight story window. Locke survived, but was paralyzed from the waist down.He began working for a box company. He wanted to do a Walkabout tour of the Australian Outback, but when he showed up in a wheelchair, the company said he couldn't go. They sent Locke home on Flight 815.",
					"Hurley's dad left when Hurley was a boy. This is when his addiction to food began.As an adult, Hurley was in a mental hospital after walking out onto a deck, which then collapsed, killing 4 people. He blamed his weight.After getting rid of his imaginary friend Dave, Hurley was released from the hospital and moved back in with his mother. Shortly after, he won the lottery, using numbers one of the other mental hospital patients repeated over and over. Ever since winning, bad things happen to people around Hurley.He bought Mr. Clucks, but a reporter, Tricia Tanaka, was killed when a meteor hit the restaurant while she was doing a piece on Hurley. His dad returned, but Hurley was suspicious that his father just wanted Hurley's money, so he didn't listen to his father when his father said that Hurley wasn't cursed.Hurley went to Australia to find Sam Toomey to find out more about the numbers he'd used to win the lottery.",
					"In flashbacks, we learned that Ben came to the island as a boy, was shot by Sayid, went to the hostiles, grew up to work for Dharma, then joined the hostiles. He personally killed his father while the rest of the initiative was gassed. He also stole Rousseau's baby instead of killing Rousseau on Charles orders. He made sure Charles was banished.",
					"Sayid was captured and Mr. Inman taught him to torture so that Sayid could torture his own commanding officer in order to get information.Later, Sayid uses his torturing skills and his superior, Omar, tells him that he's doing a great job and will soon be transferred to intelligence.A woman is captured and Sayid recognizes her as his childhood friend, Nadia. He urges her to give him some names, but she refuses and he helps her to escape.Later, the CIA wanted Sayid's help to recover C-4 explosives and offered to tell him where Nadia was in return. Sayid turned on his former roommate, Essam, to get the information, but tried to get Essam to run away. Instead, Essam killed himself. Sayid talked the CIA into letting him stay one more day to claim Essam's body, which then put him on Flight 815." };
			for (int i = 0; i < names.length; i++) {
				ContentValues initialValues = new ContentValues();
				initialValues.put(KEY_NAME, names[i]);
				initialValues.put(KEY_DESC, descs[i]);
				initialValues.put(KEY_BIO, bios[i]);

				db.insert(DATABASE_TABLE, null, initialValues);
			}
		}

		// replace older schema
		@Override
		public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
			Log.w(TAG, "Upgrading database from version " + oldVersion + " to " + newVersion
					+ ", which will destroy all old data");
			db.execSQL("DROP TABLE IF EXISTS characters");
			onCreate(db);
		}
	}

	/**
	 * Constructor - takes the context to allow the database to be
	 * opened/created
	 * 
	 * @param ctx
	 *            the Context within which to work
	 */
	public LostDbAdapter(Context ctx) {
		this.mCtx = ctx;
	}

	/**
	 * Open the lost database. If it cannot be opened, try to create a new
	 * instance of the database. If it cannot be created, throw an exception to
	 * signal the failure
	 * 
	 * @return this (self reference, allowing this to be chained in an
	 *         initialization call)
	 * @throws SQLException
	 *             if the database could be neither opened or created
	 */
	public LostDbAdapter open() throws SQLException {
		mDbHelper = new DatabaseHelper(mCtx);
		mDb = mDbHelper.getWritableDatabase();
		return this;
	}

	public void close() {
		mDbHelper.close();
	}

	/**
	 * Create a new character using the parameters provided. If the character is
	 * successfully created return the new rowId for that character, otherwise
	 * return a -1 to indicate failure.
	 * 
	 * @return rowId or -1 if failed
	 */
	public long createCharacter(String name, String desc, String bio) {
		ContentValues initialValues = new ContentValues();
		initialValues.put(KEY_NAME, name);
		initialValues.put(KEY_DESC, desc);
		initialValues.put(KEY_BIO, bio);

		return mDb.insert(DATABASE_TABLE, null, initialValues);
	}

	/**
	 * Delete the character with the given rowId
	 * 
	 * @param rowId
	 *            id of character to delete
	 * @return true if deleted, false otherwise
	 */
	public boolean deleteCharacter(long rowId) {

		return mDb.delete(DATABASE_TABLE, KEY_ROWID + "=" + rowId, null) > 0;
	}

	/**
	 * Return a Cursor over the list of all characters in the database
	 * 
	 * @return Cursor over all characters
	 */
	public Cursor fetchAllCharacters() {
		// query(table, columns, select stmt, select args, group clause, having,
		// order
		return mDb.query(DATABASE_TABLE, new String[] { KEY_ROWID, KEY_NAME, KEY_DESC, KEY_BIO },
				null, null, null, null, null);
	}

	/**
	 * Return a Cursor positioned at the character that matches the given rowId
	 * 
	 * @param rowId
	 *            id of character to retrieve
	 * @return Cursor positioned to matching character, if found
	 * @throws SQLException
	 *             if note could not be found/retrieved
	 */
	public Cursor fetchCharacter(long rowId) throws SQLException {
		// query(table, columns, select stmt, select args, group
		// clause, having, order
		Cursor mCursor = mDb.query(DATABASE_TABLE, new String[] { KEY_ROWID, KEY_NAME,
				KEY_DESC, KEY_BIO }, KEY_ROWID + "=" + rowId, null, null, null, null, null);
		if (mCursor != null) {
			mCursor.moveToFirst();
		}
		return mCursor;
	}
}
